<template>
  <div class="member-page container">
    <section class="member-page__hero card">
      <div class="member-page__intro">
        <h2>会员中心 · 企业协同门户</h2>
        <p>
          登录后可办理交易、库存核实、订单追踪以及结算开票等任务。页面设计参考
          <code>server/docs/user_org_design.md</code> 与财务/通知模块文档。
        </p>
        <div class="member-page__badges">
          <span>多角色协同</span>
          <span>流程可追溯</span>
          <span>配置驱动</span>
        </div>
      </div>
      <div class="member-page__status card">
        <template v-if="isLoggedIn">
          <h3>{{ profile.nickname || profile.username || "企业采购账号" }}</h3>
          <p class="status__meta">
            手机号：{{ profile.phone || "已脱敏" }} · 身份：采购员
          </p>
          <button class="btn btn--ghost" @click="goCart">前往购物车</button>
        </template>
        <template v-else-if="partial">
          <h3>待完成登录流程</h3>
          <p class="status__meta">
            {{ partial.message || actionMessages[partialAction] }}
          </p>
          <button class="btn btn--primary" @click="continuePartial">
            {{ partialAction === "need_bind_phone" ? "绑定手机号" : "完善认证资料" }}
          </button>
        </template>
        <template v-else>
          <h3>尚未登录</h3>
          <p class="status__meta">登录后同步企业账号、订单及消息数据。</p>
          <div class="status__actions">
            <button class="btn btn--primary" @click="openLogin">立即登录</button>
            <button class="btn btn--ghost" @click="openRegister">注册企业账号</button>
          </div>
        </template>
      </div>
    </section>

    <el-alert
      v-if="partial && !isLoggedIn"
      :title="actionMessages[partialAction]"
      type="warning"
      show-icon
      class="member-page__alert"
    />

    <PartialBindPhonePanel
      v-if="partialAction === 'need_bind_phone'"
      :partial="partial"
      @completed="handlePartialCompleted"
    />

    <CompanyVerificationPanel
      v-if="partialAction === 'need_verify_identity'"
      @submitted="handleVerificationSubmitted"
    />

    <section v-if="displayPortal" class="member-page__tabs card">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="交易协同" name="trade">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="购物车与核实">
              购物车对接 <code>trade/Cart</code>，可发起库存核实、批量下单。
            </el-descriptions-item>
            <el-descriptions-item label="订单全局视角">
              通过 <code>trade/Order</code> 获取订单状态，联动物流、售后。
            </el-descriptions-item>
            <el-descriptions-item label="通知推送">
              Gateway Worker 推送核实、支付、物流事件，支持桌面系统通知点击回调。
            </el-descriptions-item>
            <el-descriptions-item label="任务驱动">
              支持审批链、异常处理、积分兑换、工厂聚乐部活动等业务待办。
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="企业资料" name="org">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="企业认证">
              绑定公司信息、执照扫描、三方核验，参考 <code>user/CompanyVerificationService</code>。
            </el-descriptions-item>
            <el-descriptions-item label="发票信息">
              维护发票抬头、税号、邮寄地址，关联 <code>settlement/Invoice</code> 模块。
            </el-descriptions-item>
            <el-descriptions-item label="地址与员工">
              管理多仓收货地址及员工账号，依赖 <code>org/OrgMemberService</code>。
            </el-descriptions-item>
            <el-descriptions-item label="安全策略">
              设备指纹、登录日志、权限矩阵全部可追溯，配合 <code>sys/Menu</code> 配置。
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="财务结算" name="finance">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="对账与结算">
              月度任务汇总卖家订单，生成结算单，对应 <code>settlement/Statement</code>。
            </el-descriptions-item>
            <el-descriptions-item label="开票申请">
              支持在线提交开票申请、邮寄跟踪，参考 <code>settlement/InvoiceService</code>。
            </el-descriptions-item>
            <el-descriptions-item label="资金托管">
              支付完成后进入平台暂存账户，票据审核通过后自动付款。
            </el-descriptions-item>
            <el-descriptions-item label="积分与权益">
              购物车积分兑换工厂福利，结合 <code>notify</code> 消息触达。
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
      </el-tabs>
    </section>

    <section class="member-page__shortcuts">
      <article
        v-for="item in quickLinks"
        :key="item.route.name"
        class="shortcut card"
        @click="navigate(item.route, item.requiresAuth)"
      >
        <h3>{{ item.title }}</h3>
        <p>{{ item.description }}</p>
        <span class="shortcut__cta">{{ item.cta }}</span>
      </article>
    </section>

    <MemberCenterSection v-if="displayPortal" :partial-action="partialAction" />

    <section class="member-page__timeline card">
      <h3>采购协同里程碑</h3>
      <el-timeline>
        <el-timeline-item timestamp="T+0" placement="top">
          登录/注册后绑定企业信息，购物车发起首次库存核实。
        </el-timeline-item>
        <el-timeline-item timestamp="T+1" placement="top">
          卖家在核实队列回复库存与价格，自动通知采购与财务。
        </el-timeline-item>
        <el-timeline-item timestamp="T+2" placement="top">
          订单确认后触发结算任务与物流调度，实时同步轨迹。
        </el-timeline-item>
        <el-timeline-item timestamp="T+3" placement="top">
          买家确认收货，平台进入月度结算，发票审核通过自动放款。
        </el-timeline-item>
      </el-timeline>
    </section>
  </div>
</template>

<script setup>
import { computed, inject, ref } from "vue";
import { useRouter } from "vue-router";
import MemberCenterSection from "../components/MemberCenterSection.vue";
import PartialBindPhonePanel from "../components/member/PartialBindPhonePanel.vue";
import CompanyVerificationPanel from "../components/member/CompanyVerificationPanel.vue";
import { useUserStore } from "../store/user";
import { message } from "../utils/message";

const router = useRouter();
const userStore = useUserStore();
const appBridge = inject("appBridge", null);

const isLoggedIn = computed(() => userStore.isLoggedIn);
const profile = computed(() => userStore.profile || {});
const partial = computed(() => userStore.partial);
const partialAction = computed(() => userStore.partialAction);
const displayPortal = computed(() => isLoggedIn.value || Boolean(partial.value));

const activeTab = ref("trade");

const actionMessages = {
  need_bind_phone: "请绑定手机号完成账号激活",
  need_verify_identity: "请完善企业认证资料后继续下单"
};

const quickLinks = [
  {
    title: "购物车",
    description: "管理采购需求，发起库存核实或批量下单。",
    cta: "进入购物车 →",
    route: { name: "cart" },
    requiresAuth: true
  },
  {
    title: "核实记录",
    description: "查看卖家反馈、进度与附件信息，保持流程透明。",
    cta: "查看核实详情 →",
    route: { name: "verification" },
    requiresAuth: true
  },
  {
    title: "我的订单",
    description: "追踪付款、发货、签收及售后，支持导出与对账。",
    cta: "前往订单中心 →",
    route: { name: "orders" },
    requiresAuth: true
  }
];

const openLogin = () => {
  appBridge?.openLogin?.();
};

const openRegister = () => {
  appBridge?.openRegister?.();
};

const goCart = () => {
  router.push({ name: "cart" });
};

const continuePartial = () => {
  const targetId =
    partialAction.value === "need_verify_identity"
      ? "company-verification"
      : "partial-bind-phone";
  const target = document.getElementById(targetId);
  if (target) {
    target.scrollIntoView({ behavior: "smooth" });
  } else if (!isLoggedIn.value) {
    message.info("请先完成页面下方的待办任务");
  }
};

const navigate = (route, requiresAuth) => {
  if (requiresAuth && !isLoggedIn.value && !partial.value) {
    openLogin();
    return;
  }
  router.push(route);
};

const handlePartialCompleted = (result) => {
  if (result?.partial) {
    if (result.action === "need_verify_identity") {
      message.info("手机号绑定成功，请继续完善企业认证资料");
    } else {
      message.info(result.message || "手机号已绑定，请按照提示继续操作");
    }
  }
};

const handleVerificationSubmitted = (company) => {
  if (company?.status === 0) {
    message.info("认证资料已提交，请等待运营审核");
  }
};
</script>

<style scoped lang="scss">
.member-page {
  display: flex;
  flex-direction: column;
  gap: 32px;
  padding-bottom: 64px;
}

.member-page__hero {
  display: grid;
  grid-template-columns: minmax(0, 2fr) minmax(0, 1fr);
  gap: 24px;
  padding: 32px;

  @media (max-width: 960px) {
    grid-template-columns: 1fr;
  }
}

.member-page__intro {
  display: flex;
  flex-direction: column;
  gap: 16px;

  h2 {
    margin: 0;
  }

  p {
    margin: 0;
    color: var(--gray-600);

    code {
      background: var(--gray-100);
      border-radius: 6px;
      padding: 2px 6px;
      font-size: 12px;
      color: var(--primary-color);
    }
  }
}

.member-page__badges {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;

  span {
    padding: 6px 12px;
    border-radius: 999px;
    background: var(--primary-light);
    color: var(--primary-color);
    font-weight: 600;
    font-size: 12px;
  }
}

.member-page__status {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 24px;
  border-radius: 16px;
  background: linear-gradient(140deg, #f4f7fe 0%, #ffffff 100%);
  border: 1px solid var(--gray-100);

  h3 {
    margin: 0;
  }
}

.status__meta {
  margin: 0;
  font-size: 14px;
  color: var(--gray-600);
}

.status__actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.member-page__alert {
  margin-top: -8px;
}

.member-page__tabs {
  padding: 24px;
}

.member-page__shortcuts {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
}

.shortcut {
  padding: 24px;
  border-radius: 16px;
  background: #ffffff;
  border: 1px solid var(--gray-100);
  cursor: pointer;
  display: flex;
  flex-direction: column;
  gap: 10px;
  transition: box-shadow 0.2s ease;

  &:hover {
    box-shadow: 0 16px 32px rgba(15, 23, 42, 0.12);
  }

  h3 {
    margin: 0;
  }

  p {
    margin: 0;
    color: var(--gray-600);
    font-size: 14px;
  }
}

.shortcut__cta {
  margin-top: auto;
  color: var(--primary-color);
  font-weight: 600;
}

.member-page__timeline {
  padding: 28px;

  h3 {
    margin: 0 0 16px;
  }
}

.btn {
  border: none;
  border-radius: 12px;
  padding: 10px 22px;
  font-weight: 600;
  cursor: pointer;

  &--primary {
    background: var(--primary-color);
    color: #fff;
  }

  &--ghost {
    background: var(--gray-100);
    color: var(--primary-color);
  }
}
</style>
